package com.loong.game2048.interceptor;

import com.loong.game2048.Exception.BizException;
import com.loong.game2048.Exception.BizExceptionCodeEnum;
import com.loong.game2048.annotation.Authorize;
import com.loong.game2048.module.User;
import com.loong.game2048.server.UserServer;
import com.loong.game2048.util.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 *
 * @author lyx
 * @date 2020/5/8 21:35
 */
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Autowired
    private UserServer userServer;

    //拦截器：请求之前preHandle
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();

        //检查有没有需要用户权限的注解
        //如果有注解Authorize，就需要验证token
        if (method.isAnnotationPresent(Authorize.class)) {
            Authorize userLoginToken = method.getAnnotation(Authorize.class);
            if (userLoginToken.required()) {

                String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token

            // 执行认证
            if (token == null) {
                throw new BizException("无效请求，没有带token");
            }
            // 获取 token 中的 user id
            String userId = ResultUtils.getOpenId(httpServletRequest);
//                    // 添加request参数，用于传递userid
//                    httpServletRequest.setAttribute("currentUser", userId);
                // 根据userId 查询用户信息
                User user = userServer.getUserById(userId);
                if (user == null) {
                    throw new BizException(BizExceptionCodeEnum.NO_LOGIN);
                }

                return true;
            }
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    //拦截器：请求之后：afterCompletion
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {

    }


}
